package org.example.managere.controller.feibiao;

import lombok.RequiredArgsConstructor;
import org.example.managere.dto.feibiao.AmArchivesFailureDto;
import org.example.managere.service.feibiao.AmArchivesFailureService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 电机故障记录控制器
 */
@RestController
@RequestMapping("/api/feibiao/failure")
@RequiredArgsConstructor
public class AmArchivesFailureController {

    private final AmArchivesFailureService failureService;

    /**
     * 获取所有故障记录（分页）
     */
    @GetMapping
    public ResponseEntity<?> getAllFailures(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String sort) {
        try {
            Pageable pageable;
            if (sort != null && !sort.isEmpty()) {
                String[] sortParams = sort.split(",");
                String sortField = sortParams[0];
                Sort.Direction direction = (sortParams.length > 1 && sortParams[1].equalsIgnoreCase("desc"))
                        ? Sort.Direction.DESC : Sort.Direction.ASC;
                pageable = PageRequest.of(page, size, Sort.by(direction, sortField));
            } else {
                // 默认按ID升序排列
                pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "failureId"));
            }
            
            Page<AmArchivesFailureDto> resultPage = failureService.findAll(pageable);
            return ResponseEntity.ok(resultPage);
        } catch (Exception e) {
            e.printStackTrace();
            String errorMsg = e.getMessage() != null ? e.getMessage() : "处理请求时发生未知错误";
            // Check for Hibernate LazyInitializationException
            if (errorMsg.contains("could not initialize proxy") || errorMsg.contains("no session")) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(java.util.Map.of("error", "数据加载错误: 懒加载问题，请检查JPA配置和DTO查询实现"));
            }
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(java.util.Map.of("error", errorMsg));
        }
    }

    /**
     * 根据ID获取故障记录
     */
    @GetMapping("/{failureId}")
    public ResponseEntity<?> getFailureById(@PathVariable Integer failureId) {
        try {
            return failureService.findById(failureId)
                    .map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(java.util.Map.of("error", e.getMessage() != null ? e.getMessage() : "处理请求时发生未知错误"));
        }
    }

    /**
     * 创建故障记录
     */
    @PostMapping
    public ResponseEntity<?> createFailure(@RequestBody AmArchivesFailureDto failureDto) {
        try {
            return new ResponseEntity<>(failureService.save(failureDto), HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(java.util.Map.of("error", e.getMessage() != null ? e.getMessage() : "创建故障记录时发生错误"));
        }
    }

    /**
     * 更新故障记录
     */
    @PutMapping("/{failureId}")
    public ResponseEntity<?> updateFailure(
            @PathVariable Integer failureId,
            @RequestBody AmArchivesFailureDto failureDto) {
        try {
            if (failureDto.getFailureId() != null && !failureId.equals(failureDto.getFailureId())) {
                return ResponseEntity.badRequest().body(java.util.Map.of("error", "路径ID与请求体ID不匹配"));
            }
            failureDto.setFailureId(failureId);
            return ResponseEntity.ok(failureService.update(failureDto));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(java.util.Map.of("error", e.getMessage() != null ? e.getMessage() : "更新故障记录时发生错误"));
        }
    }

    /**
     * 删除故障记录
     */
    @DeleteMapping("/{failureId}")
    public ResponseEntity<?> deleteFailure(@PathVariable Integer failureId) {
        try {
            failureService.deleteById(failureId);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(java.util.Map.of("error", e.getMessage() != null ? e.getMessage() : "删除故障记录时发生错误"));
        }
    }

    /**
     * 根据电机ID查询故障记录
     */
    @GetMapping("/by-motor")
    public ResponseEntity<?> findByMotorId(@RequestParam String motorId) {
        try {
            return ResponseEntity.ok(failureService.findByMotorId(motorId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(java.util.Map.of("error", e.getMessage() != null ? e.getMessage() : "查询故障记录时发生错误"));
        }
    }

    /**
     * 根据故障类型查询故障记录
     */
    @GetMapping("/by-type")
    public ResponseEntity<?> findByFailureType(@RequestParam String failureType) {
        try {
            return ResponseEntity.ok(failureService.findByFailureType(failureType));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(java.util.Map.of("error", e.getMessage() != null ? e.getMessage() : "查询故障记录时发生错误"));
        }
    }

    /**
     * 根据是否修复状态查询故障记录
     */
    @GetMapping("/by-repaired")
    public ResponseEntity<List<AmArchivesFailureDto>> findByRepaired(@RequestParam Boolean repaired) {
        return ResponseEntity.ok(failureService.findByRepaired(repaired));
    }
} 